package com.example.nutritionmate.controller;

import com.example.nutritionmate.dto.CreateMealRecordDTO;
import com.example.nutritionmate.dto.MealRecordDTO;
import com.example.nutritionmate.entity.MealRecord;
import com.example.nutritionmate.entity.MealNutrition;
import com.example.nutritionmate.entity.User;
import com.example.nutritionmate.service.MealService;
import com.example.nutritionmate.service.RecordService;
import com.example.nutritionmate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/record")
public class RecordController {

    @Autowired
    private MealService mealService;

    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;

    // 获取当前用户的所有餐食记录及相关信息
    @GetMapping("/recordsByDay")
    public ResponseEntity<?> getUserMealRecords(@AuthenticationPrincipal UserDetails userDetails, @RequestParam String date) {
        Optional<User> optionalUser = userService.findByUsername(userDetails.getUsername());
        User user = optionalUser.get();
        List<MealRecord> records = mealService.getMealRecordsByUser(user);

        // 转换为DTO或自定义响应对象
        List<MealRecordDTO> recordDTOs = records.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        return ResponseEntity.ok(recordDTOs);
    }


    /**
     * 添加一条当前用户指定日期指定餐次的饮食记录
     *
     * @param userDetails          认证后的用户详情
     * @param createMealRecordDTO  请求传来的饮食记录DTO
     * @return                     保存后的 MealRecord 实体
     */
    @PostMapping("/add")
    public ResponseEntity<?> addMealRecord(@AuthenticationPrincipal UserDetails userDetails,
                                           @RequestBody CreateMealRecordDTO createMealRecordDTO) {
        // 查找当前用户
        User user = userService.findByUsername(userDetails.getUsername())
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 添加饮食记录
        MealRecord mealRecord = recordService.addMealRecord(user, createMealRecordDTO);
        if (mealRecord != null) {
            return ResponseEntity.ok(true);
        }
        return ResponseEntity.ok(false);
    }

    // 转换 MealRecord 实体为 DTO
    private MealRecordDTO convertToDTO(MealRecord record) {
        MealRecordDTO dto = new MealRecordDTO();
        dto.setRecordId(record.getRecordId());
        dto.setMealType(record.getMeal().getMealType().toString());
        dto.setDate(record.getMeal().getDate());

        // 计算总营养
        double totalCalories = record.getMealNutritions().stream()
                .filter(mn -> "Calories".equalsIgnoreCase(mn.getNutritionFact().getNutritionNameEn()))
                .mapToDouble(MealNutrition::getAmount)
                .sum();
//        dto.setTotalCalories(totalCalories);

        // 更多营养项可以按需添加

        return dto;
    }
}
